package com.example.javaapitest.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class functionUtil {
    private static final Map<String, Class<? extends functionInterface>> functionsMap = new HashMap<String, Class<? extends functionInterface>>();
    static {
        //bodyfile 特殊处理，这个bodyfile主要是应对POST有上传文件的情况。
        functionsMap.put("bodyfile", null);
        List<Class<?>> clazzes = classFinder.getAllAssignedClass(functionInterface.class);
        clazzes.forEach((clazz) -> {
            try {
                // function
                functionInterface tempFunc = (functionInterface) clazz.newInstance();
                String referenceKey = tempFunc.getReferenceKey();
                if (referenceKey.length() > 0) { // ignore self
                    functionsMap.put(referenceKey, tempFunc.getClass());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                //TODO
            }
        });
    }

    public static boolean isFunction(String functionName){
        return functionsMap.containsKey(functionName);
    }

    public static String getValue(String functionName,String[] args){
        try {
            return functionsMap.get(functionName).newInstance().execute(args);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }
}
